package com.example.stock.service.impl;

import com.example.stock.excel.StockIntroduce;
import com.example.stock.service.IndustryDataService;
import com.example.stock.service.StockService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class IndustryDataServiceImpl implements IndustryDataService {

    StockService stockService;

    @Autowired
    public void setStockService(StockService stockService) {
        this.stockService = stockService;
    }

    private final Map<String, Set<String>> tagsMap = new HashMap<>();

    private final Map<String, Set<String>> stocksTagMap = new HashMap<>();

    @PostConstruct
    public void init() {
        stockService.getStockInfosMap().forEach((k, v) -> {
            String tag = v.getTag();
            if (tag != null) {
                tagsMap.computeIfAbsent(tag, i -> new HashSet<>()).add(v.getStock());
                stocksTagMap.computeIfAbsent(v.getStock(), i -> new HashSet<>()).add(tag);
            }

            StockIntroduce stockIntroduce = stockService.getStockIntroduce(v.getStock());
            if (stockIntroduce != null && stockIntroduce.getTag() != null) {
                Arrays.stream(stockIntroduce.getTag().split(";")).forEach(t -> {
                    tagsMap.computeIfAbsent(t, i -> new HashSet<>()).add(v.getStock());
                    stocksTagMap.computeIfAbsent(v.getStock(), i -> new HashSet<>()).add(t);
                });
            }
        });
    }

    @Override
    public Map<String, Set<String>> getTagsMap() {
        return tagsMap;
    }

    @Override
    public List<String> getStocksByTag(String tag) {
        return tagsMap.get(tag) != null ? new ArrayList<>(tagsMap.get(tag)) : null;
    }

    @Override
    public List<String> getTagsByStock(String stock) {
        return stocksTagMap.get(stock) != null ? new ArrayList<>(stocksTagMap.get(stock)) : null;
    }
}
